package com.dsy.xiangcun_manage.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsy.tools.common.utils.AliyunOSSUtil;
import com.dsy.tools.common.utils.MailUtils;
import com.dsy.tools.common.utils.QueryObj;
import com.dsy.tools.entity.TbActivity;
import com.dsy.tools.entity.TbActivityJoin;
import com.dsy.tools.entity.TbTou;
import com.dsy.xiangcun_manage.service.ITbActivityJoinService;
import com.dsy.xiangcun_manage.service.ITbActivityService;
import com.dsy.xiangcun_manage.service.ITbTouService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dsy
 * @since 2021-02-11
 */
@Controller
@RequestMapping("/act")
public class TbActivityController {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ITbActivityService activityService;

    @Autowired
    private ITbActivityJoinService activityJoinService;

    @Autowired
    private ITbTouService tbTouService;

    /**
     * 分页获取所有活动
     * @param m
     * @param page
     * @param limit
     * @param queryObj
     * @return
     */
    @RequestMapping("/getAllAct")
    public String getAllAct(Model m, @RequestParam(defaultValue = "1") long page, @RequestParam(defaultValue = "10") long limit, QueryObj queryObj){
        QueryWrapper<QueryObj> wrapper = new QueryWrapper<>();
        wrapper.setEntity(queryObj);
        IPage<TbActivity> actPage = activityService.getAllAct(page,limit,wrapper);
        m.addAttribute("actPage",actPage);
        m.addAttribute("page",page);
        m.addAttribute("queryObj",queryObj);
        return "/activity/act-base";

    }


    /**
     * 跳转到创建活动的页面
     * @return
     */
    @RequestMapping("/createNewAct")
    public String createNewAct(){
        return "/activity/act-add";
    }
    /**
     * 创建活动
     * @param tbActivity
     * @param session
     * @return
     */
//    @RequestMapping("/addAct")
//    @ResponseBody
//    public Integer addAct(TbActivity tbActivity, MultipartFile file ,HttpSession session) {
//        logger.info("文件上传");
//        String filename = file.getOriginalFilename();
//        System.out.println(filename);
//        TbTou tbTou = (TbTou) session.getAttribute("tbTou");
//        if (tbActivity.getAcTitle() != null && !"".equals(tbActivity.getAcTitle().trim()) && tbActivity.getAcDesc() != null && !"".equals(tbActivity.getAcDesc().trim()) && tbActivity.getAcStartTime() != null && tbActivity.getAcEndTime() != null) {
//            tbActivity.setAcPer(tbTou.getUserId());
//            tbActivity.setAcStatus(1); //后台创建活动自动有效
//            try {
//                if (!"".equals(filename.trim())) {
//                    File newFile = new File(filename);
//                    FileOutputStream os = new FileOutputStream(newFile);
//                    os.write(file.getBytes());
//                    os.close();
//                    file.transferTo(newFile);
//                    // 上传到OSS
//                    String uploadUrl = AliyunOSSUtil.upLoad(newFile);
//                    newFile.delete();
////                    tbTou.setTouImg(uploadUrl);
//                    tbActivity.setAcBarimg(uploadUrl);
//                }
//                else {
//                    tbActivity.setAcBarimg("https://xcagedu.oss-cn-beijing.aliyuncs.com/dev/baiyangdian/default/defaultimg.jpg");
//                }
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//            tbActivity.setAcCreateTime(LocalDateTime.now());
//            List<TbActivity> list = activityService.list(new QueryWrapper<TbActivity>().eq("ac_title", tbActivity.getAcTitle()).select("ac_title"));
//            if (list != null) {
//                for (TbActivity activity : list) {
//                    if (activity.getAcTitle().equals(tbActivity.getAcTitle())) {
//                        return 2;
//                    }
//                }
//            }
//            boolean b = activityService.save(tbActivity);
//            if (b) {
//                return 1;
//            } else {
//                return 0;
//            }
//        }
//        return 0;
//    }

    @RequestMapping("/addAct")
    public String addAct(TbActivity tbActivity, MultipartFile file ,HttpSession session) {
        logger.info("文件上传");
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        TbTou tbTou = (TbTou) session.getAttribute("tbTou");
        if (tbActivity.getAcTitle() != null && !"".equals(tbActivity.getAcTitle().trim()) && tbActivity.getAcDesc() != null && !"".equals(tbActivity.getAcDesc().trim()) && tbActivity.getAcStartTime() != null && tbActivity.getAcEndTime() != null) {
            tbActivity.setAcPer(tbTou.getUserId());
            tbActivity.setAcStatus(1); //后台创建活动自动有效
            try {
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    // 上传到OSS
                    String uploadUrl = AliyunOSSUtil.upLoad(newFile);
                    newFile.delete();
//                    tbTou.setTouImg(uploadUrl);
                    tbActivity.setAcBarimg(uploadUrl);
                }
                else {
                    tbActivity.setAcBarimg("https://xcagedu.oss-cn-beijing.aliyuncs.com/dev/2023-04-02/b31ec9031c1541dda4a6429c322c1d95-ewm.png");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            tbActivity.setAcCreateTime(LocalDateTime.now());
            List<TbActivity> list = activityService.list(new QueryWrapper<TbActivity>().eq("ac_title", tbActivity.getAcTitle()).select("ac_title"));
            if (list != null) {
                for (TbActivity activity : list) {
                    if (activity.getAcTitle().equals(tbActivity.getAcTitle())) {
                        return "redirect:/act/addAct";
                    }
                }
            }
            activityService.save(tbActivity);
        }
        return "redirect:/act/getAllAct";
    }



        /**
         * 根据id获取活动信息
         * @param m
         * @param acId
         * @return
         */
    @RequestMapping("/getActById")
    public String getActById(Model m,Integer acId){
        TbActivity act=activityService.getActById(acId);
        m.addAttribute("act",act);
        return "/activity/act-edit";
    }

    /**
     * 根据id获取活动信息
     * @param m
     * @param acId
     * @return
     */
    @RequestMapping("/getActDetailById")
    public String getActDetailById(Model m,Integer acId){
        TbActivity act=activityService.getActById(acId);
        m.addAttribute("act",act);
        return "/activity/act-modifi";
    }

    /**
     * 根据id获取修改活动信息
     * @param activity
     * @return
     */
    @RequestMapping("/updateActs")
    public String updateAct(TbActivity activity, MultipartFile file){
        String filename = file.getOriginalFilename();
        try {
        if (!"".equals(filename.trim())) {
            File newFile = new File(filename);
            FileOutputStream os = new FileOutputStream(newFile);
            os.write(file.getBytes());
            os.close();
            file.transferTo(newFile);
            // 上传到OSS
            String uploadUrl = AliyunOSSUtil.upLoad(newFile);
            newFile.delete();
            activity.setAcBarimg(uploadUrl);
        }
        else {
            activity.setAcBarimg("https://xcagedu.oss-cn-beijing.aliyuncs.com/dev/2023-04-02/b31ec9031c1541dda4a6429c322c1d95-ewm.png");
        }}catch (Exception e){
            e.printStackTrace();
        }
        activityService.updateById(activity);
        return "redirect:/act/getAllAct";
    }


    /**
     * 根据Id更新活动
     * @param tbActivity
     * @return
     */
    @RequestMapping("/updateActById")
    @ResponseBody
    public Integer updateActById(TbActivity tbActivity){
        activityService.updateById(tbActivity);
        TbActivityJoin activityJoin = new TbActivityJoin();
        activityJoin.setUserId(tbActivity.getAcPer());
        activityJoin.setAcId(tbActivity.getAcId());
        boolean b = activityJoinService.save(activityJoin);
        if(b){
            TbTou tbTou = tbTouService.getOne(new QueryWrapper<TbTou>().select("name", "email").eq("user_id", tbActivity.getAcPer()));
            if(tbActivity.getAcStatus()==1&& tbTou.getEmail()!=null){
                try {
                    MailUtils.sendMail(tbTou.getEmail(),"你申请的用户活动审核通过啦"," ");
                    return 1;
                } catch (MessagingException e) {
                    e.printStackTrace();
                    return 2;
                }
            }
            if(tbActivity.getAcStatus()==2&& tbTou.getEmail()!=null){
                try {
                    MailUtils.sendMail(tbTou.getEmail(),"你申请的用户活动未通过审核","请重新申请活动");
                    return 1;
                } catch (MessagingException e) {
                    e.printStackTrace();
                    return 2;
                }
            }
        }
        return 2;
    }

    /**
     * 查询参与活动的用户
     * @param m
     * @param acId
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/getActJoinById")
    public String getActJoinById(Model m,Integer acId,@RequestParam(defaultValue = "1") long page, @RequestParam(defaultValue = "10") long limit){
        IPage<TbTou> touPage = tbTouService.getActJoinById(new Page<TbTou>(page,limit),acId);
        m.addAttribute("touPage",touPage);
        m.addAttribute("page",page);
        m.addAttribute("acId",acId);
        return "/activity/actStu-look";
    }

    /**
     * 删除加入活动的用户
     * @param userIds
     * @param acId
     * @return
     */
    @RequestMapping("/delActJoinById")
    public String delActJoinById(@RequestParam("userId") List<Integer> userIds,Integer acId){
        QueryWrapper<TbActivityJoin> wrapper = new QueryWrapper<>();
        wrapper.in("user_id",userIds);
        activityJoinService.remove(wrapper);
        return "redirect:/act/getActJoinById?acId="+acId;
    }


    /**
     * 根据id删除
     * @param acIds
     * @return
     */
    @RequestMapping("/delActById")
    public String delActById(@RequestParam("acId") List<Integer> acIds){
        activityService.removeByIds(acIds);
        QueryWrapper<TbActivityJoin> wrapper = new QueryWrapper<>();
        wrapper.in("ac_id",acIds);
        activityJoinService.remove(wrapper);
        return "redirect:/act/getAllAct";
    }

}
